function isScrolledToBottom(element) {
  return element.scrollHeight - element.scrollTop === element.clientHeight;
}

const fetch = window.fetch;
// 获取列表更新 index为key
const resultAll = {};
const showList = [];
let has_more = false;
let fetchPage = 1;
let countSum = 0;

function fetchListData(page = 1, callback) {
  fetch("https://buyin.jinritemai.com/selection_cart_pc_api/card/m_get_card", {
    headers: {
      "content-type": "application/json",
    },
    body: `{"page_size":20,"key_word":"","view_type":0,"common_filter":{},"page":${page},"version":2}`,
    method: "POST",
    mode: "cors",
    credentials: "include",
  })
    .then((res) => res.json())
    .then((res) => {
      const { code, data = {}, msg } = res;
      if (code != 0) {
        console.log("请求错误", msg);
        return;
      }

      if (data?.cart_view_card?.length < 1) {
        callback([]);
        return;
      }

      const { cards = [], has_more: _has_more = false } =
        data?.cart_view_card[0];

      const ids = cards
        .map((e, i) => ({
          id: e.product_card?.product_id,
          key: (fetchPage - 1) * 20 + i, // 计算准确的下标
          promotion_status: e.product_card?.promotion_info?.promotion_status,
          good_ratio: e.product_card?.business_operation_info?.good_ratio,
        }))
        .filter((e) => e.promotion_status === 2);
      has_more = _has_more;
      if (_has_more) fetchPage += 1;
      callback(ids);
    });
}

async function fetchDetail({ id, key, good_ratio }) {
  const r = await fetch(
    `https://buyin.jinritemai.com/pc/decision/comment/list?product_id=${id}&page=1&page_size=20&type=0&tag_id=-1`,
    {
      body: null,
      method: "GET",
      mode: "cors",
      credentials: "include",
    }
  );
  const res = await r.json();
  const { code, msg, total } = res;
  if (code != 0) {
    console.log(msg);
    return Promise.resolve({ key, tol: 0 });
  }

  return Promise.resolve({ key, tol: total, good_ratio });
}

function showTotalHtml(tol) {
  const newDiv = document.createElement("div"); // 创建新的div元素
  newDiv.textContent = `总评价数：${tol}`;
  return newDiv;
}

const container = document.getElementsByClassName("auxo-sp-infinit-container");

const batchGetDetails = (ids) => {
  const promises = ids.filter((e) => !!e.id).map((e) => fetchDetail(e)); // 过滤掉空的id
  Promise.all(promises).then((arr) => {
    arr.forEach((res) => {
      const { key, tol, good_ratio } = res;
      resultAll[key] = { tol, good_ratio };
    });
    // 显示到网页上
    if (container.length) {
      const element = container[0];
      element.children.forEach((child, index) => {
        const list = child.children;
        if (
          resultAll[index] &&
          !showList.includes(index) &&
          list.length &&
          list.length > 7
        ) {
          const { tol, good_ratio } = resultAll[index];
          // 总评价数大于30，且好评率小于85%，就高亮显示
          const isHightLight = tol > 30 && Number(good_ratio) < 85;
          showList.push(index);
          const col = list[6];
          col.style.flexDirection = "column";
          if (isHightLight) {
            col.style.backgroundColor = "pink";
          }

          col.appendChild(showTotalHtml(tol));
        }
      });
    }
  });
};

const scrollContainer = document.getElementById("portal"); // 替换为你的滚动容器选择器

scrollContainer.addEventListener("scroll", function () {
  if (isScrolledToBottom(scrollContainer)) {
    console.log("已经滚动到底部了！");
    if (has_more) {
      fetchPage += 1;
      fetchListData(fetchPage, (ids) => {
        batchGetDetails(ids);
      });
    }
  }
});

fetchListData(fetchPage, (ids) => {
  batchGetDetails(ids);
});
